// oss 文件上传
import React from 'react';
import { observer } from 'mobx-react-lite';
import { Upload, Button } from 'antd';
import { UploadOutlined, ArrowUpOutlined } from '@ant-design/icons';
import { UploadProps, UploadFile } from 'antd/lib/upload/interface';
import { config } from '~/config/config';

interface Props extends Omit<UploadProps, 'value' | 'onChange'>{
  value?: UploadProps['fileList']
  onChange?: UploadProps['onChange']
  uploadIcon?: string // 自定义图标
  max?: number // 默认限制最大上传个数：20，0 为不限制
  size?: number // 默认限制最大上传尺寸：10 MB
  isDisabled?: boolean // 是否隐藏上传按钮
}

export const FileUploader = observer((props: Props) => {
  const {
    value,
    onChange,
    max = 20,
    size = 10000,
    uploadIcon,
    isDisabled,
    ...rest
  } = props;

  const handleChange = ({ fileList }: any) => {
    if (value && value.length > 0) {
      value.forEach((v) => {
        if (v.status === 'done') {
          v.url = `${config.ossUrl}${v.response.data as string}`;
        }
      });
    }

    if (onChange) {
      onChange(fileList);
    }
  };

  const uploadButton = uploadIcon ? <ArrowUpOutlined />
    : <Button>
      <UploadOutlined /> Choose file
    </Button>;

  // 上传按钮展示
  const setUploadButton = (_value: Array<UploadFile> | undefined, _max: number) => {
    if (_max === 0) {
      // 不限制上传个数
      return uploadButton;
    }

    if (isDisabled) {
      return null;
    }

    if (!_value) {
      return uploadButton;
    }

    if (_value.length < _max) {
      return uploadButton;
    }

    return null;
  };

  const uploadConfig = {
    action: `${config.remoteUrl}/file/oss_upload`,
    listType: 'text' as const,
    ...'value' in props ? {
      fileList: value,
    } : {},
    onChange: handleChange,
    withCredentials: true,
  };

  return (
    <div className="clearfix">
      <Upload
        {...uploadConfig}
        {...rest}
      >
        {setUploadButton(value, max)}
      </Upload>
    </div>
  );
});
